<?php

namespace App\Store\Controllers\Basic;

use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Basic\TemplateQuality;
use App\Store\Services\Order\OrderDeposit as ServicesOrderOrderDeposit;
use App\Store\Services\Order\OrderMaintenance as ServicesOrderOrderMaintenance;
use App\Store\Services\Order\OrderRecovery as ServicesOrderOrderRecovery;
use App\Store\Services\Order\OrderSales as ServicesOrderOrderSales;
use App\Store\Services\Order\OrderRecharge as ServicesOrderOrderRecharge;
use Illuminate\Http\Request;
use App\Store\Validate\Basic\TemplateQuality as ValidateBasicTemplateQuality;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;

/**
 * 模板、质保单
 */
class TemplateQualityController extends Controller
{


    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['store_ids', 'type', 'quality_name', 'quality_url', 'remark', 'is_default_value']);
        $Validate = new ValidateBasicTemplateQuality();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $store_ids = $req_data['store_ids'];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);

        if ($req_data['type'] == 3) {
            $report_json = config('warranty.other_order_json');
        } else {
            $report_json = config('warranty.order_json');
        }

        DB::beginTransaction();
        try {
            foreach ($store_ids as $store_id) {
                $quality_data = $req_data + [
                        'store_id' => $store_id,
                        'cp_id' => $cp_id,
                        'create_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'report_json' => $report_json
                    ];
                TemplateQuality::create($quality_data);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'store_id', 'type', 'quality_name', 'quality_url', 'remark']);
        $Validate = new ValidateBasicTemplateQuality('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $old_type = TemplateQuality::where('id', $req_data['id'])->value('type');

        $quality_data = $req_data + [
                'update_at' => time(),
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];

        if ($old_type != $req_data['type']) {
            if ($req_data['type'] == 2) {
                $report_json = config('warranty.order_json');
            } elseif ($req_data['type'] == 3) {
                $report_json = config('warranty.other_order_json');
            } else {
                $report_json = config('warranty.order_json');
            }
            $quality_data['report_json'] = $report_json;

        }


        TemplateQuality::where('id', $req_data['id'])->update($quality_data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function dodel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateBasicTemplateQuality('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        TemplateQuality::where('id', $req_data['id'])->update([
            'is_del' => 2,
            'update_at' => time(),
        ]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    public function dodefaultvalue(Request $request)
    {
        $id = $request->only(['id']);
        if (!$id) {
            return response()->json(['code' => '001', 'msg' => 'id不能为空']);
        }
        $TemplateQualityObj = new TemplateQuality();
        $res = $TemplateQualityObj->editDefaultvalue($request);

        if ($res !== false) {
            return response()->json(['code' => '000', 'msg' => '设置成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '修改失败']);
        }
    }

    public function getListDefaultId(array $data)
    {
        $id = 0;
        if (empty($data['list'])) {
            return $id;
        }
        foreach ($data['list'] as $item) {
            if ($item['is_default_value'] == 2) {
                $id = $item['id'];
                break;
            }
        }
        return $id;
    }

    public function getlist(Request $request)
    {
        $list = TemplateQuality::getList($request);
        if (!empty($list)) {
            $default_value = $this->getListDefaultId($list);
            $list['default_value'] = $default_value;
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    public function doexport(Request $request)
    {
        $list = TemplateQuality::getList($request)['list'];
        $exceldata = [];
        $storeNames = array_unique(array_map(function ($item) {
            return $item['storeinfo']['store_name'];
        }, $list));
        $row = [
            ['quality_name' => '质保单模板'],
            ['quality_name' => '所属门店：' . join(',', $storeNames)],
            [
                'quality_name' => '质保单名称',
                'type' => '质保单类型',
                'store_name' => '门店名称',
                'is_default_value' => '是否默认',
                'remark' => '备注',
                'report_json_file_path' => '模板文件路径',
            ]
        ];
        $type_arr = ['1' => '销售开单', '2' => '纯回收开单', '3' => '其他开单'];
        foreach ($list as $val) {
            if (!$val['report_json_file_path']) {
                $path = 'template/quality/' . md5(time() . mt_rand(1000, 9999));
                Storage::put($path, $val['report_json']);
                $val['report_json_file_path'] = $path;
                TemplateQuality::where(['id' => $val['id']])->update(['report_json_file_path' => $path]);
            }
            $exceldata[] = [
                'quality_name' => $val['quality_name'],
                'type' => $type_arr[$val['type']] ?? '',
                'store_name' => $val['storeinfo']['store_name'],
                'is_default_value' => ($val['is_default_value'] == '1') ? '' : '是',
                'remark' => $val['remark'],
                'report_json_file_path' => $val['report_json_file_path']
            ];
        }

        $filename = '质保单模板导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);


    }

    public function doimport(Request $request)
    {
        $store_ids = $request->store_ids ?? [];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);
        if (count($store_ids) <= 0) {

            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;
        try {
            if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
                $file = storage_path() . $filepathname;
                $data = Excel::toArray(null, $file)[0];
                $type_arr = ['销售开单' => 1, '纯回收开单' => 2, '其他开单' => 3];
                foreach ($store_ids as $store_id) {
                    $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
                    if (!$storeinfo) {
                        return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                    }
                }
                $ins_data = [];
                foreach ($data as $key => $val) {
                    if ($key == 0 && (strpos('质保单模板', (string)$val[0]) !== false)) {
                        continue;
                    }
                    if ($key == 1 && (strpos((string)$val[0], '所属门店') !== false)) {
                        continue;
                    }

                    if (strpos((string)$val[0], '质保单名称') !== false || strpos((string)$val[1], '质保单类型') !== false || strpos((string)$val[2], '质保单类型') !== false) { //表头跳过
                        continue;
                    }
                    if (count($val) != 6) {
                        return response()->json(['code' => '001', 'msg' => '导入数据格式错误']);
                    }

                    if ($val[0] == '合计' || empty($val[0])) {
                        continue;
                    }

                    $valdata = [
                        'cp_id' => $cp_id,
                        'type' => isset($type_arr[$val[1]]) ? $type_arr[$val[1]] : 1,
                        'quality_name' => $val[0],
                        'is_default_value' => !empty($val[3]) ? (($val[3] == '是') ? 2 : 1) : 1,
                        'remark' => !empty($val[4]) ? strval($val[4]) : '',
                        'create_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                    ];

                    if ($valdata['type'] == 2) {
                        $report_json = config('warranty.order_json');
                    } elseif ($valdata['type'] == 3) {
                        $report_json = config('warranty.other_order_json');
                    } else {
                        $report_json = config('warranty.order_json');
                    }
                    $valdata['report_json'] = empty($val[5]) ? $report_json : (!empty(Storage::get($val[5])) ? Storage::get($val[5]) : $report_json);

                    foreach ($store_ids as $store_id) {

                        $item = $valdata;
                        $path = 'template/quality/' . md5(time() . mt_rand(1000, 9999));
                        Storage::put($path, $valdata['report_json']);
                        $item['report_json_file_path'] = $path;
                        $item['store_id'] = $store_id;
                        $ins_data[] = $item;
                    }
                }

                TemplateQuality::insert($ins_data);
                return response()->json(['code' => '000', 'msg' => '数据导入成功']);
            } else {
                return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '导入失败,请检查文件']);
        }

    }

    public function designtag(Request $request)
    {

        $id = $request->id ?? 0;
        $info = TemplateQuality::where(['id' => $id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '质保单不存在']);
        }

        if (empty($info->report_json)) {
            $report_json = config('warranty.order_json');
        } else {
            $report_json = $info->report_json;
        }

        return response()->json(json_decode($report_json, true));
    }

    public function qualityTag(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        if (empty($accountinfo)) {
            return response()->json(['code' => '001', 'msg' => '登陆的账号信息不存在']);
        }

        $cp_id = $accountinfo['cp_id'];
        $id = $request->id ?? 0;
        $type = $request->type ?? '';
        $account_id = $accountinfo['id'] ?? 0;

        $orderId = $request->order_id ?? 0;
        if (empty($type)) {
            return response()->json(['code' => '001', 'msg' => '类型不能为空']);
        }

        if (empty($orderId)) {
            return response()->json(['code' => '001', 'msg' => '订单id不能为空']);
        }


        $info = TemplateQuality::where(['id' => $id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '质保单不存在']);
        }


        $url = env('APP_URL') . "/store/basic/templatequality/qualityPrint?print_temp_id=$id&type=$type&cp_id=$cp_id&order_id=$orderId&account_id=$account_id";

        return response()->json(['code' => '000', 'msg' => '成功', 'data' => ['url' => $url]]);
    }


    public function savedesigntag(Request $request)
    {
        $id = $request->id ?? 0;
        $info = TemplateQuality::where(['id' => $id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '质保单不存在']);
        }
        $report_json = $request->report_json ?? '';
        if (!$info->report_json_file_path) {
            $path = 'template/quality/' . md5(time() . mt_rand(1000, 9999));
            Storage::put($path, $report_json);
            $info->report_json_file_path = $path;
        } else {
            $path = $info->report_json_file_path;
            Storage::put($path, $report_json);
        }
        TemplateQuality::where(['id' => $id, 'is_del' => 1])->update(['report_json' => $report_json, 'report_json_file_path' => $info->report_json_file_path]);
        return response()->json(['code' => '000', 'msg' => '保存成功']);
    }

    public function copyquality(Request $request)
    {
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = TemplateQuality::where(['id' => $id, 'is_del' => 1, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '标签不存在']);
        }
        // /'store_ids', 'tag_name', 'remark'
        $tag_data = [
            'store_id' => $info->store_id,
            'cp_id' => $cp_id,
            'quality_name' => $info->quality_name,
            'quality_url' => $info->quality_url,
            'remark' => $info->remark,
            'create_at' => time(),
            'update_at' => time(),
            'create_account_id' => $accountinfo['id'],
            'create_account_real_name' => $accountinfo['real_name'],
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'report_json' => $info->report_json
        ];
        TemplateQuality::create($tag_data);

        return response()->json(['code' => '000', 'msg' => '复制成功']);


    }


    /**
     *  数据打印接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function qualityPrint(Request $request)
    {
        $type = $request->type ?? 0;
        $orderId = $request->order_id ?? 0;
        $print_temp_id = $request->print_temp_id ?? 0;

        $info = TemplateQuality::where(['id' => $print_temp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '质保单不存在']);
        }


        switch ($type) {
            // 1销售开单
            case 1:
                $data = ServicesOrderOrderSales::getOrderPrintData($orderId, $request, true);
                break;
            //2定金开单
            case 2:
                $data = ServicesOrderOrderDeposit::getOrderPrintData($orderId);
                break;
            //3充值开开单
            case 3:
                $data = ServicesOrderOrderRecharge::getOrderPrintData($orderId);
                break;
            //4纯回收开单
            case 4:
                $data = ServicesOrderOrderRecovery::getOrderPrintData($orderId, $request,true);
                break;
            //5维修开单
            case 5:
                $data=ServicesOrderOrderMaintenance::getOrderPrintData($orderId);
                break;
            default:
                $data=[];
        }

        //$data['info']=[$data['info']];
        //$data['goodsdata']=$data['goodsdata'];

        $res['code'] = 0;
        $res['data'] = $data;
        $res['message'] = 'ok';
        $res['templet'] = json_decode($info->report_json, true);
        $res['version'] = '1.0.1';

        return response()->json($res);

    }
}
